package com.example.demo.service.impl;

import java.io.IOException;
import java.sql.ResultSet;

import com.alibaba.fastjson.JSON;
import com.example.demo.*;
import com.example.demo.controller.WebSocketController;
import com.example.demo.service.SQLInterface;
import com.example.demo.service.SQLData;
import com.normalClasses.eye.*;

import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

@Slf4j
@Service("CustomerService")
public class CustomerService implements SQLInterface, Log_Exit_timeline, SQLData {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public UserManagement getPeople(String username, String password) {
        // TODO Auto-generated method stub
        //数据库可能存在不唯一情况
        try {
            String sql = "select nickname,userimg,T1.username,password,T2.status from t_people_right_static t1,t_people_login_status t2 WHERE t1.username='" + username + "' AND T2.username='" + username + "' and t1.password='" + password + "'";
            UserManagement_ex1 user = jdbcTemplate.queryForObject(sql, new RowMapper<UserManagement_ex1>() {
                @Override
                public UserManagement_ex1 mapRow(ResultSet arg0, int arg1) throws SQLException {
                    UserManagement_ex1 user = new UserManagement_ex1();
                    user.setUsername(arg0.getString("username"));
                    user.setPassword(arg0.getString("password"));
                    user.setLoginstatus(arg0.getString("status"));
                    user.setNickname(arg0.getString("nickname"));
                    user.setUserimg(arg0.getString("userimg"));
                    return user;
                }
            });
            return user;
        } catch (Exception e) {
            // TODO: handle exception
            throw e;
        }
    }

    @Override
    public int judge_people_exist(String username, String password) {
        // TODO Auto-generated method stub
        List user = (List) jdbcTemplate.queryForList("select * from t_people_right_static where `username`= '" + username + "'and `password`='" + password + "'");
        return user.size();
    }

    @Override
    public void change_loginstatus(String username, String status) {
        // TODO Auto-generated method stub
        jdbcTemplate.update("UPDATE t_people_login_status set `status`='" + status + "' where `username`= '" + username + "'");
        //System.out.println(username+"执行了更改登录状态");
    }

    @Override
    public void storage_cookiestatus(String cookie, String username) {
        // TODO Auto-generated method stub
        long time = new Date().getTime();
        String timeString = String.valueOf(time);
        jdbcTemplate.update("INSERT INTO `t_people_login_cookies`(`username`, `cookies`, `generate_time`) VALUES (?,?,?)", username, cookie, timeString);
        log.info(LogUtil.logSpec(username + "new cookie state inserted"));
    }

    @Override
    public boolean check_cookiestatus(String cookie) {
        // TODO Auto-generated method stub
        List user = (List) jdbcTemplate.queryForList("select generate_time,username  from t_people_login_cookies where `cookies` ='" + cookie + "'");
        if (user.size() == 1) {
            //当前时间戳
            long now_time = new Date().getTime();
            //提取list第一行数据
            Map check = (Map) user.get(0);
            //检查cookie是否过期
            if (now_time - Long.valueOf((String) check.get("generate_time")) >= 60 * 60 * 24 * 3 * 1000) {
                jdbcTemplate.update("UPDATE t_people_login_status set `status`='false' where `username` ='" + check.get("username") + "'");
                log.warn(LogUtil.logSpec(cookie + "Expired"));
                return false;
            } else {
                log.info(LogUtil.logSpec(cookie + "is normal!"));
                return true;
            }
        } else if (user.size() == 0) {
            log.info(LogUtil.logSpec(cookie + "is not exist!", 7));
            return false;
        } else if (user.size() > 1) {
            log.error(LogUtil.logSpec(cookie + "multiple existence, system has logic bug"));
            return true;
        }
        log.error(LogUtil.logSpec("check_cookiestatus Error level error occurs, the condition is skipped directly, and SQL injection attack may be encountered", 9));
        return false;
    }

    @Value("${test.dns}")
    private String test_dns;

    @Override
    public String[] load_img_list(int level) {
        //TODO Auto-generated method stub
        List user = (List) jdbcTemplate.queryForList("select * from peopleimg");
        String[] picture = new String[user.size()];
        for (int i = 0; i < user.size(); i++) {
            Map pic = (Map) user.get(i);
            picture[i] = this.test_dns + "img/img/" + pic.get("picture");
        }
        System.out.println("执行了加载图片资源操作！");
        return picture;
    }

    @Autowired
    private com.example.demo.repository.AutoMessageHandler AutoMessageHandler;

    @Override
    public boolean Updatelogtime(String cookie, String timepoint) {
        // TODO Auto-generated method stub
        String username = AutoMessageHandler.Auto_getusername(cookie);
        if (username != null) {
            //使登陆时间存储中只有唯一的有效时间
            List user1 = (List) jdbcTemplate.queryForList("select * from t_people_login_time where `username` ='" + username + "' and `recent_bit`=0");
            if (user1.size() > 0) {
                jdbcTemplate.update("UPDATE t_people_login_time set `recent_bit`=1 where `recent_bit` =0 and `username` ='" + username + "'");
            }
            jdbcTemplate.update("INSERT INTO `t_people_login_time`(`username`, `login_time`, `recent_bit`) VALUES (?,?,?)", username, timepoint, 0);//对数据库表格数据进行更新
            log.info(LogUtil.logSpec("update " + username + "login time"));//输出用户的登陆时间
            return true;
        } else return false;
    }

    @Override
    public boolean Updateexitime(String cookie, String timepoint) {
        // TODO Auto-generated method stub
        String username = AutoMessageHandler.Auto_getusername(cookie);
        if (username != null) {
            List user1 = (List) jdbcTemplate.queryForList("select * from t_people_logout_time where `username` ='" + username + "' and `recent_bit`=0");
            if (user1.size() > 0) {
                jdbcTemplate.update("UPDATE t_people_logout_time set `recent_bit`=1 where `recent_bit` =0 and `username` ='" + username + "'");
            }
            jdbcTemplate.update("INSERT INTO `t_people_logout_time`(`username`, `logout_time`, `recent_bit`) VALUES (?,?,?)", username, timepoint, 0);//对数据库表格数据进行更新
            //将登陆状态改变
            this.change_loginstatus(username, "false");
            log.info(LogUtil.logSpec("update " + username + "logout time"));//输出用户的登陆时间
            return true;
        } else return false;
    }

    @Override
    public void storage_ip(String username, String ip) {
        // TODO Auto-generated method stub
        long timestamp = System.currentTimeMillis();
        String timeString = String.valueOf(timestamp);
        jdbcTemplate.update("INSERT INTO `t_people_login_ips`(`username`, `ip`, `login_time`) VALUES (?,?,?)", username, ip, timeString);
    }

    @Override
    public void activation_socketmessage(String cookie) {
        // TODO Auto-generated method stub
        String usernameString = this.AutoMessageHandler.Auto_getusername(cookie);
        List user = (List) jdbcTemplate.queryForList("select * from t_people_message_hint where `username` ='" + usernameString + "'");
        if (user.size() > 0) {
            //更新定时任务
            jdbcTemplate.update("update `t_people_message_hint` set `status`='true' where  `username` = '" + usernameString + "'");
            //对结果进行log记录，特别是短时间多次刷新情况
            Map people = (Map) user.get(0);
            String status = (String) people.get("status");
            if (status.equals("true")) {
                //对权限打开的用户记录log多次刷新
                log.error(LogUtil.logSpec("this member" + usernameString + " mabye multiply refresh", 4));
            }
        } else {
            //对初次登陆者，进行一条插入权限的操作
            jdbcTemplate.update("INSERT INTO `t_people_message_hint`(`username`,`status`) VALUES (?,?)", usernameString, "true");
        }
        log.info(LogUtil.logSpec(usernameString + "timing message prompt function activated"));
    }

    @Override
    public void substitude_people(String cookie) {
        // TODO Auto-generated method stub
        //获得当前在线的userid
        String[] userids = WebSocketController.getonlineUserid();
        String now_username = AutoMessageHandler.Auto_getusername(cookie);
        //遍历比较当前在线userid，找到同一账号主体
        for (String userid : userids) {
            if (AutoMessageHandler.Auto_getusername(userid).equals(now_username)) {
                message message = new message();
                message.setTitle("异常警告");
                message.setContent("您当前的账号已被另一账号主体占用，如果并非您的操作，请及时反馈给我们，或者及时更改你的密码");
                String msg = JSON.toJSONString(message);
                //执行抢占操作函数
                try {
                    //给监控系统处理队列加入一条消息,异常编号为0，id默认为0，不起任何作用
                    monitor_res_obj user = new monitor_res_obj(now_username, 0, 0);
                    AutoRealTimeMonitoring.monitoring_message.push(user);
                    //关掉会话连接
                    WebSocketController.close_session(userid, msg);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    log.error(LogUtil.logSpec("websocket.close_session has problem"));
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    log.error(LogUtil.logSpec("Auto_real_time_monitoring has push problem"));
                }
                return;
            }
        }
    }

    @Override
    public void storage_login_time(String username) {
        // TODO Auto-generated method stub
        List user = (List) jdbcTemplate.queryForList("SELECT `recent_bit` FROM `t_people_login_time` WHERE `username` ='" + username + "' and `recent_bit`=0 ");//逻辑层面并不允许在插入新的登入时间时前面还有没有使用过的登入时间
        if (user.size() > 0) {
            //将bit位置强制改动
            jdbcTemplate.update("UPDATE `t_people_login_time` SET `recent_bit`=1 WHERE `username`='" + username + "'");
        }
        long timestamp = System.currentTimeMillis();
        String timeString = String.valueOf(timestamp);
        //插入一条登入时间条
        jdbcTemplate.update("INSERT INTO `t_people_login_time`(`username`,`login_time`,`recent_bit`) VALUES (?,?,?)", username, timeString, 0);
    }

    @Override
    public void register_people(String username, String password, String email) {
        // TODO Auto-generated method stub
        String space = "";
        jdbcTemplate.update("INSERT INTO `t_people_right_static`(`username`, `password`, `admin`,`email`,`nickname`,`userimg`) VALUES (?,?,?,?,?,?)", username, password, 5, email, space, space);//对数据库表格数据进行更新
    }

    @Override
    public int judge_people_exist(String username) {
        // TODO Auto-generated method stub
        List user = (List) jdbcTemplate.queryForList("select username from t_people_right_static where `username`= '" + username + "'");
        return user.size();//
    }

    @Override
    public void register_login(String username, String ip, String cookie) {
        // TODO Auto-generated method stub
        //插入一条登陆状态
        jdbcTemplate.update("INSERT INTO t_people_login_status (`username`,`status`) VALUES (?,?)", username, "ture");
        this.storage_ip(username, ip);
        this.storage_cookiestatus(cookie, username);
        this.activation_socketmessage(cookie);
        //log.info(LogUtil.logSpec(username+"注册并自动登陆了");
    }

    @Override
    public Map<String, String> transmit_nickname_headimg_list(int sum_number) {
        // TODO Auto-generated method stub
        List number = (List) jdbcTemplate.queryForList("select count(*) from t_nickname_userimg");
        Map numMap = (Map) number.get(0);
        //获取一个表的长度
        //System.out.println(numMap.get("count(*)").getClass().toString());
        long indexnum = (long) numMap.get("count(*)");
        List user = (List) jdbcTemplate.queryForList("select nickname,userimg from t_nickname_userimg where `dirty_bit`=0 limit " + (long) (indexnum * Math.random()) + "," + sum_number);
        int listsize;
        if ((listsize = user.size()) > 0) {
            //初始化一个map
            Map<String, String> maplist = new HashMap<String, String>();
            for (int i = 0; i < listsize; i++) {
                Map usermap = (Map) user.get(i);
                maplist.put((String) usermap.get("nickname"), (String) usermap.get("userimg"));
            }
            return maplist;
        }
        return null;
    }
}
